package cn.bbs.ba.util;

import java.io.File;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;



public class ToolsXML {
	
	/**
	 * Read xml
	 * @param url address
	 * @return xml
	 * @throws Exception
	 */
	public static HashMap<String, String> readXML(String url) {
		
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder;
		HashMap<String, String> map = null;
		try {
			builder = factory.newDocumentBuilder();
			File xmlFile = new File(url);
			Document doc = builder.parse(xmlFile);
			Element rootElement = doc.getDocumentElement();
			NodeList children = rootElement.getChildNodes();
			int cnt = children.getLength();
			map = new HashMap<String, String>();
			if (cnt != 0) {
				elementRead(children, map);
			}
		} catch (Exception e) {
			;
		}
		
		return map;
	}
	
	/**
	 * ceng zhijian de duchu
	 * @param children
	 * @param map
	 */
	private static void elementRead(NodeList children, HashMap<String, String> map) {
		Node current = null;
		int cnt = children.getLength();
		for (int i = 0; i < cnt; i ++) {
			current = children.item(i);
			if (current.getNodeType() == Node.ELEMENT_NODE) {
				Element element = (Element) current;
				map.put(element.getTagName(), element.getTextContent());
				NodeList nextChildren = element.getChildNodes();
				int nextCnt = nextChildren.getLength();
				if (nextCnt != 0) {
					elementRead(nextChildren, map);
				}
			}
		}
	}
	
   
}
